import {
  Avatar,
  Breadcrumb,
  Button,
  Card,
  Divider,
  Message,
  Space,
  Tag,
  Tooltip,
} from "@arco-design/web-react";
import { css } from "@emotion/css";
import { ReactNode, SyntheticEvent, useEffect, useState } from "react";
// import { VideoModal } from "../../components/VideoModal";
import { ActivityReport } from "../../components/ElderReport/ActivityReport.tsx";
import { RiskHandleRecord } from "../../components/ElderReport/RiskHandleRecord.tsx";
import { NursingReport } from "../../components/ElderReport/NursingReport.tsx";
import { SleepReport } from "../../components/ElderReport/SleepReport.tsx";
import {
  IconClockCircle,
  IconCloud,
  IconLocation,
  IconMan,
  IconPhone,
  IconRight,
  IconUser,
  IconVideoCamera,
  IconWoman,
} from "@arco-design/web-react/icon";
import { useQuery } from "react-query";
import { useAPI } from "../../hooks/useAPI.ts";
import { EditUserInfoModal } from "../../components/EditUserInfoModal";
import { Sex } from "../../api/types/system-user.ts";
import { useParams } from "../../hooks/useParams.ts";
import { Link } from "../../components/Link";
import dayjs from "dayjs";
import { useCameraStatus } from "../../hooks/useCameraStatus.ts";
import { CameraStatus } from "../../api/types/camera.ts";
import { AppBar, Tab } from "@mui/material";
import { TabContext, TabPanel } from "@mui/lab";
import Grid from "@mui/material/Grid";
import { FinalRiskType } from "../../api/types/elder-risk.ts";
import Tabs from "@mui/material/Tabs";

export interface InfoItem {
  label: ReactNode;
  icon: ReactNode;
  value: ReactNode;
}

export default function ElderReport() {
  const api = useAPI();
  const { userId } = useParams<{ userId: string }>();
  const [isEditing, setIsEditing] = useState(false);
  const [value, setValue] = useState<string>("1");
  const [action, setAction] = useState<any>(null);
  const [riskLevel, setRiskLevel] = useState<any>(null);
  const [info, setInfo] = useState<any>(null);
  const [radar, setRadar] = useState<any>(null);
  const [nursing, setNursing] = useState<any>(false);

  const handleChange = (_event: SyntheticEvent, newValue: string) => {
    setValue(newValue);
  };

  const getPeopleIn = () => {
    if (
      action?.remark === undefined ||
      action.remark === null ||
      action.remark === "" ||
      action.remark === "null"
    )
      return 0;
    return action
      ? parseInt(action.remark.split(",")[1]) +
          parseInt(action.remark.split(",")[2])
      : 0;
  };

  const { data, refetch } = useQuery(
    ["elder-report", userId],
    async () => {
      try {
        const response = await api.getSystemUserById(userId!);
        return response.data.data;
      } catch (error) {
        if (error instanceof Error) {
          Message.error(error.message);
        } else {
          Message.error("操作失败，请稍后重试");
        }
      }
    },
    {
      enabled: !!userId,
    }
  );
  const getResponse = async () => {
    const response = await api.getElderActionByUser(userId);
    setAction(response.data.data[0]);
    setRiskLevel(response.data.action?.actionStatus ?? FinalRiskType.RiskMid);
    setNursing(response.data.nursing);
    const rd = response.data.radar?.data;
    if (rd) {
      let reference;
      switch (JSON.parse(rd).EventInfo.Type) {
        case "PersonDisappearEvent":
          reference = "无人";
          break;
        case "PersonAppearEvent":
          reference = "有人";
          break;
        case "FallOverAlarm":
          reference = "有人跌倒";
          break;
        case "PersonGetup":
          reference = "起身";
          break;
        default:
          reference = "";
      }
      setRadar(reference);
    }
    const tmp = response.data.action?.info;
    setInfo(tmp ? JSON.parse(tmp) : null);
  };
  useEffect(() => {
    getResponse();
    const timer = setInterval(async () => {
      await getResponse();
    }, 1000); //every 1 second

    return () => {
      clearInterval(timer);
    };
  }, []);

  // @ts-ignore
  const tagColor = {
    [FinalRiskType.RiskMid]: "orange",
    [FinalRiskType.High]: "red",
    [FinalRiskType.RiskNone]: "green",
  }[riskLevel ?? FinalRiskType.RiskNone];

  const { text } = useCameraStatus(data?.cameraStatus ?? CameraStatus.unbound);
  const infos: InfoItem[] = data
    ? [
        data?.birth
          ? {
              label: "生日",
              value: `${data.birth}（${dayjs().diff(
                dayjs(data?.birth),
                "year"
              )}岁）`,
              icon: <IconClockCircle />,
            }
          : null,
        radar
          ? {
              label: "厕所",
              value: radar,
              icon: <IconCloud />,
            }
          : null,
        data?.sex
          ? {
              label: "性别",
              value: {
                [Sex.Man]: "男",
                [Sex.Woman]: "女",
              }[data.sex],
              icon: {
                [Sex.Man]: <IconMan />,
                [Sex.Woman]: <IconWoman />,
              }[data.sex],
            }
          : null,
        {
          label: "实时位置",
          value: `${
            action?.status && action.status !== "" && action.status !== null
              ? action.status
              : "未知"
          }`,
          icon: <IconLocation />,
        },
        {
          label: "生活管家", // TODO: 待确认
          value: `${data.managers?.join(",") ?? "-"}`,
          icon: <IconUser />,
        },
        data?.phonenumber
          ? {
              label: "联系方式",
              value: `${data?.phonenumber}`,
              icon: <IconPhone />,
            }
          : null,
        {
          label: "摄像头情况",
          value: text,
          icon: <IconVideoCamera />,
        },
      ]
        .filter((x) => x)
        .map((x) => x as InfoItem)
    : [];

  function a11yProps(index: number) {
    return {
      id: `full-width-tab-${index}`,
      "aria-controls": `full-width-tabpanel-${index}`,
    };
  }

  return (
    <>
      <EditUserInfoModal
        visible={isEditing}
        onClose={() => setIsEditing(false)}
        onSuccess={async () => {
          setIsEditing(false);
          await refetch();
        }}
        title="编辑长辈信息"
        defaultData={data}
        isEdit={true}
      />
      <Breadcrumb
        className={css`
          padding: 12px;
          border-radius: 1px;
          font-weight: bold;
          border-left: 5px solid rgb(var(--primary-6));
        `}
        separator={<IconRight />}
      >
        <Breadcrumb.Item style={{ fontWeight: 400 }}>
          <Link
            to="/homepage/index"
            style={{
              transition: "color 0.3s",
              fontWeight: "bold",
              fontSize: "15px",
            }}
          >
            返回工作台
          </Link>
        </Breadcrumb.Item>
        {data ? <Breadcrumb.Item>{`${data?.nickName}`}</Breadcrumb.Item> : null}
      </Breadcrumb>

      <Grid container spacing={2}>
        <Grid item lg={2} md={2} xs={12}>
          <Card
            bordered={false}
            className={css`
              border: 1px solid rgba(47, 43, 61, 0.16);
              border-radius: 6px;
              margin-top: 15px;
              height: calc(100% - 15px);
            `}
          >
            <Space
              direction="vertical"
              className={css`
                display: flex;
                gap: 1px;
              `}
            >
              <Space
                direction="vertical"
                className={css`
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  margin-top: 5px;
                `}
              >
                <Avatar size={70} shape="square">
                  {data?.avatar ? (
                    <img src={data?.avatar} alt={data?.avatar} />
                  ) : (
                    data?.nickName
                  )}
                </Avatar>

                <p
                  className={css`
                    font-size: 14px;
                    font-weight: 500;
                    line-height: 150%;
                  `}
                >
                  {data?.nickName}
                </p>
                {!nursing && (
                  <Tag
                    className={css`
                      text-align: center;
                      height: 80px;
                    `}
                    color={tagColor}
                    bordered
                  >
                    当前屋内：{getPeopleIn()}人 <br />
                    当前动作：{action?.actCn ?? ""} <br />
                    {info
                      ? `心率： ${Math.round(
                          info.HealthData.HeartFreqAverage
                        )} | 
                       呼吸： ${Math.round(info.HealthData.BreathFreqAverage)}`
                      : null}
                  </Tag>
                )}
                {nursing && (
                  <Tag
                    className={css`
                      text-align: center;
                      height: 80px;
                    `}
                    color="orange"
                    bordered
                  >
                    当前屋内：{getPeopleIn()}人 <br />
                    正在护理
                    <br />
                    {info
                      ? `心率： ${Math.round(
                          info.HealthData.HeartFreqAverage
                        )} | 
                       呼吸： ${Math.round(info.HealthData.BreathFreqAverage)}`
                      : null}
                  </Tag>
                )}
              </Space>
              <Divider />
              <Space
                direction="vertical"
                className={css`
                  display: flex;
                  gap: 10px;
                `}
              >
                {infos.map((info, index) => (
                  <div
                    key={index}
                    className={css`
                      display: flex;
                      gap: 8px;
                      align-items: center;
                    `}
                  >
                    <div
                      className={css`
                        width: 34px;
                        height: 34px;
                        background: #fff4e4;
                        border-radius: 4px;
                        display: flex;
                        justify-content: center;
                        align-items: center;

                        svg {
                          width: 22px;
                          height: 22px;
                          color: rgb(var(--primary-6));
                        }
                      `}
                    >
                      {info.icon}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <Tooltip content={info.value}>
                        <p
                          style={{
                            fontSize: "14px",
                            whiteSpace: "nowrap",
                            width: "100%",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                          }}
                        >
                          {info.value}
                        </p>
                      </Tooltip>
                      <p style={{ fontSize: "12px" }}>{info.label}</p>
                    </div>
                  </div>
                ))}
              </Space>
              <Divider />
              <div
                className={css`
                  display: flex;
                  justify-content: center;
                  align-items: center;
                `}
              >
                <Button type="primary" onClick={() => setIsEditing(true)}>
                  编辑
                </Button>
              </div>
            </Space>
          </Card>
        </Grid>
        <Grid item lg={10} md={7} xs={12}>
          <TabContext value={value}>
            <AppBar
              position="static"
              style={{
                marginTop: "15px",
                boxShadow: "none",
                borderRadius: "6px 6px 0 0",
                border: "1px solid rgba(47, 43, 61, 0.16)",
                backgroundColor: "white",
              }}
            >
              <Tabs
                value={value}
                onChange={handleChange}
                indicatorColor="primary"
                textColor="primary"
                variant="fullWidth"
                aria-label="full width tabs example"
                style={{ backgroundColor: "white" }}
              >
                <Tab value="1" label="活动报告" {...a11yProps(0)} />
                <Tab value="2" label="风险处理日志" {...a11yProps(2)} />
                <Tab value="3" label="护理报告" {...a11yProps(3)} />
                {/* <Tab value="4" label="睡眠报告" {...a11yProps(4)} /> */}
              </Tabs>
            </AppBar>

            <Grid item xs={12}>
              <div
                className={css`
                  padding: 10px 10px;
                  border-radius: 0 0 6px 6px;
                  border: 1px solid rgba(47, 43, 61, 0.16);
                  min-height: 702px;
                `}
              >
                <TabPanel value="1">
                  {data?.userId ? <ActivityReport user={data} /> : null}
                </TabPanel>
                <TabPanel value="2">
                  {data?.userId ? (
                    <RiskHandleRecord userId={data.userId} />
                  ) : null}
                </TabPanel>
                <TabPanel value="3">
                  {data?.roomId ? (
                    <NursingReport roomId={data.roomId} />
                  ) : (
                    <div
                      className={css`
                        text-align: center;
                        margin-top: 12px;
                      `}
                    >
                      当前用户还未绑定房间，无法查询护理报告
                    </div>
                  )}
                </TabPanel>
                <TabPanel value="4">
                  {data?.roomId ? (
                    <SleepReport roomId={data.roomId} />
                  ) : (
                    <div
                      className={css`
                        text-align: center;
                        margin-top: 12px;
                      `}
                    >
                      当前用户还未绑定房间，无法查询护理报告
                    </div>
                  )}
                </TabPanel>
              </div>
            </Grid>
          </TabContext>
        </Grid>
      </Grid>
    </>
  );
}
